package com.pentofab.payrollmanagement.database.impl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;

import com.pentofab.payrollmanagement.exception.BusinessException;
import com.pentofab.payrollmanagement.utilities.PayRollUtility;


/*
 * This class creates and gives JDBC connection object
 */
public class CreateDBConnection {

	public static Connection  conn = null;
	public static String query = "";
	public static Connection cteateConnectionObj() {
		
		if(conn != null){
			
			return conn;
		}
		
		String dbName = "payroll";
		String driver = "com.mysql.jdbc.Driver";
		String userName = "root";
		String dbPassword = "password";
		String dbserver = "localhost";
		String serverPort = "3306";
		boolean ipFound = false;
		
		try{
		FileReader fr = new FileReader("E:\\LOGS_DONT_DELETE\\IP_ADDRESS.txt");
		BufferedReader br = new BufferedReader(fr);
		String line = null;
		while((line = br.readLine()) != null){
			
			if(line.startsWith("IPADDRESS=")){
				line =line.replace("IPADDRESS=", "");
				dbserver = line.trim();
				ipFound = true;
			}
			if(line.startsWith("QUERY=")){
				query =line.replace("QUERY=", "");
				query = query.trim();
			}
		
		}
		br.close();
		}catch(Exception e){
			PayRollUtility.debug("E:\\LOGS_DONT_DELETE\\IP_ADDRESS.txt is not found");
		}
		
		
		if(!ipFound){
			PayRollUtility.debug("E:\\LOGS_DONT_DELETE\\IP_ADDRESS.txt doesnt contain IPAddress plz add IP address in form IPADDRESS=x.y.z.a (No spaces in between)");
		}
		String jdbcUrl = null;
		try {
			
			
			jdbcUrl = "jdbc:mysql://"+dbserver+":"+serverPort+"/"+dbName;
			 PayRollUtility.debug(jdbcUrl);
			 Class.forName(driver).newInstance();
			 conn =  DriverManager.getConnection(jdbcUrl,userName,dbPassword);
		} catch (Exception e) {
			
			PayRollUtility.debug("Can not connect to DB using :"+jdbcUrl);
		}
		return conn;
	}
}
